<template>
	<el-dialog
		:visible.sync="dialogVisible"
		:fullscreen="true"
		@open="init"
	>
		<el-row
			class="el-low-c"
			type="flex"
			justify="start"
			align="middle"
		>
			<el-col class="el-span-c">
				<span>代号</span>
			</el-col>
			<el-col class="el-input-normal-c">
				<el-input :readonly="true" v-model="ordermodelInEditing.Code"></el-input>
			</el-col>
			<el-col class="el-span-c">
				<span>日期</span>
			</el-col>
			<el-col class="el-input-normal-c">
				<el-date-picker
					:disabled="true"
					type="date"
					placeholder="选择日期"
					value-format="yyyy-MM-dd"
					v-model="ordermodelInEditing.DocDate"
				></el-date-picker>
			</el-col>
			<el-col class="el-span-c">
				<span>经销商</span>
			</el-col>
			<el-col class="el-input-normal-c">
				<RetailSelector
					:autocheck="true"
					@retailSelected="retailSelected"
					v-model="ordermodelInEditing.Retail"
				/>
			</el-col>
			<el-col class="el-span-c">
				<span></span>
			</el-col>
			<el-col class="el-input-normal-c">
				<el-steps
					:simple="false"
					:space="80"
					:active="this.status"
					finish-status="success"
				>
					<el-step title="打开"></el-step>
					<el-step title="审核"></el-step>
					<el-step title="受理"></el-step>
					<el-step title="确认"></el-step>
				</el-steps>
			</el-col>
		</el-row>
		<el-row
			class="el-low-c"
			type="flex"
			justify="start"
			align="middle"
		>
			<el-col class="el-span-c">
				<span>业务员</span>
			</el-col>
			<el-col class="el-input-normal-c">
				<UserSelector v-model="ordermodelInEditing.Sales" />
			</el-col>
			<el-col class="el-span-c">
				<span>备注</span>
			</el-col>
			<el-col class="el-input-large-c">
				<el-input v-model="ordermodelInEditing.Note"></el-input>
			</el-col>
		</el-row>
		<div>
			<OrderGridEditor
				ref="oge"
				:status="status"
				:rowData="orderdetailInEditing"
			/>
		</div>
		<div
			slot="title"
			style="border-bottom: 1px dashed #dcdfe6;font-size: larger;padding-bottom: 10px;"
		>
			<span>数据管理</span>
			<hr
				style="border:1 dashed "
				width="100%"
				color="#DCDFE6"
				size="1"
			/>
			<div>
				<el-button-group>
					<el-button
						size="mini"
						:disabled="!savable"
						type="primary"
						@click="onSubmit"
					>保存</el-button>
					<el-button
						size="mini"
						:disabled="!approvable"
						@click="onApprove"
					>审核</el-button>
				</el-button-group>
				<el-button-group>
					<el-button
						size="mini"
						:disabled="!savable"
						@click="showPP"
					>选产品</el-button>
					<el-button
						size="mini"
						:disabled="!savable"
						@click="addBlankRow"
					>增空行</el-button>
					<el-button
						size="mini"
						:disabled="orderdetailInEditing.length===0||!savable"
						@click="rmRow"
					>删行</el-button>
				</el-button-group>
				<el-button-group>
					<el-button
						size="mini"
						@click="dialogVisible = false"
					>关闭</el-button>
				</el-button-group>
			</div>
		</div>
		<div
			slot="footer"
			style="border-top: 1px dashed #dcdfe6;font-size: larger;padding-top: 10px;"
		></div>
		<el-dialog
			:visible.sync="pickerVisible"
			:modal="false"
		>
			<ProductionPicker
				:multiple="true"
				:autoset="true"
				ref="pp"
				@confirm="addRow"
				@finish="addRowAndClose"
				@ignore="pickerVisible=false"
			/>
		</el-dialog>
	</el-dialog>
</template>
<script>
	import CustomerSelector from '@/components/Selector/CustomerSelector'
	import UserSelector from '@/components/Selector/UserSelector'
	import RetailSelector from '@/components/Selector/RetailSelector'
	import OrderGridEditor from '@/components/GridEditor/OrderGridEditor'
	import ProductionPicker from '@/components/DataPicker/ProductionPicker.vue'

	import { setOrder, get, approveOrder } from '@/api/order'
	import { getNowFormatDate } from '@/utils/date'
	import { getCode } from '@/api/codeincrement'
	import { getPrice } from '@/api/custprice'

	import { Model } from 'vue-property-decorator'
	import { warn } from 'vue-class-component/lib/util'

	export default {
		components: {
			CustomerSelector,
			UserSelector,
			ProductionPicker,
			RetailSelector,
			OrderGridEditor
		},
		data() {
			return {
				dialogVisible: false,
				ordermodelInEditing: {},
				orderdetailInEditing: [],
				pickerVisible: false,
				busy: false
			}
		},
		computed: {
			approvable: function() {
				return this.status === 1 && this.$route.meta.approve && !this.busy
			},
			savable: function() {
				return this.status < 2 && this.$route.meta.create
			},
			status: function() {
				if (this.ordermodelInEditing.ApproveFlag === undefined) {
					return 0
				}
				if (this.ordermodelInEditing.ApproveFlag === 0) {
					return 1
				}
				if (
					this.ordermodelInEditing.ApproveFlag === 1 &&
					this.ordermodelInEditing.Status <= 1
				) {
					return 2
				}
				if (
					this.ordermodelInEditing.ApproveFlag !== undefined &&
					this.ordermodelInEditing.ApproveFlag === 1 &&
					this.ordermodelInEditing.Status > 1
				) {
					return 3
				}
			}
		},
		props: { ordermodel: Object },
		methods: {
			init() {
				if (this.ordermodel.AutoId === this.ordermodelInEditing.AutoId) return
				if (this.ordermodel.AutoId === 0) {
					this.ordermodelInEditing = this.ordermodel
					this.ordermodelInEditing.DocDate = getNowFormatDate()
					this.orderdetailInEditing = []
					getCode('SO')
						.then(response => {
							if (response.Result === 0) {
								this.ordermodelInEditing.Code = response.Data
								this.orderdetailInEditing = []
							} else {
								this.$alert(response.Message, '创建单号失败')
							}
						})
						.catch(error => {
							console.log(error)
						})
				} else {
					this.ordermodelInEditing = this.ordermodel
					this.orderdetailInEditing = []
					get(this.ordermodelInEditing.AutoId)
						.then(response => {
							if (response.Result === 0) {
								let tmp = response.Detail
								this.orderdetailInEditing = this.setTempId(tmp)
							} else {
								this.$alert(response.Message, '获取明细数据失败')
							}
						})
						.catch(error => {
							console.log(error)
						})
				}
			},
			showPP() {
				if (this.savable) {
					this.pickerVisible = true
					if (this.$refs.pp) {
						this.$refs.pp.$refs.kw.focus()
					}
				}
			},
			addBlankRow() {
				if (this.savable) {
					this.addRow([{}, {}, {}, {}, {}])
				}
			},
			retailSelected(params, obj) {
				this.ordermodelInEditing.Sales = obj.Sales
			},
			setTempId(items) {
				let obj = JSON.parse(JSON.stringify(items))
				for (let i = 0; i < obj.length; i++) {
					obj[i].minTmpid = -1 - i
				}
				return obj
			},
			onSubmit() {
				this.$refs.oge.commit()
				if (
					this.orderdetailInEditing === null ||
					this.orderdetailInEditing.length === 0
				) {
					this.$alert('资料不完整', '错误')
					return
				}
				for (let i = this.orderdetailInEditing.length; i > 0; i--) {
					if (
						!this.orderdetailInEditing[i - 1].ProductionId ||
						this.orderdetailInEditing[i - 1].ProductionId === 0
					) {
						this.orderdetailInEditing.splice(i - 1, 1)
					}
				}
				setOrder(this.ordermodelInEditing, this.orderdetailInEditing)
					.then(response => {
						if (response.Result === 0) {
							this.ordermodelInEditing = response.Data
							let tmp = response.Detail
							this.orderdetailInEditing = this.setTempId(tmp)
							this.$message('保存成功')
							this.$emit('orderSaveComplete', this.ordermodelInEditing)
						} else {
							this.$alert(response.Message, '失败')
						}
					})
					.catch(error => {
						this.$alert(error, '错误')
					})
			},
			onApprove() {
				if (this.$refs.oge.getEditStatus().length > 0) {
					this.$alert('当前表格正在编辑中，不能审核', '警告')
					return
				}
				this.busy = true
				approveOrder(this.ordermodelInEditing)
					.then(response => {
						if (response.Result === 0) {
							this.ordermodelInEditing = response.Data
							let tmp = response.Detail
							this.orderdetailInEditing = this.setTempId(tmp)
							this.$message('审核成功')
							this.$emit('orderApproveComplete', this.ordermodelInEditing)
						} else {
							this.$alert(response.Message, '失败')
							this.busy = false
						}
					})
					.catch(error => {
						this.$alert(error, '错误')
						this.busy = false
					})
			},
			addRow(productions) {
				for (let midx in productions) {
					let minTmpid = 0
					let skip = false
					for (let idx in this.orderdetailInEditing) {
						if (
							this.orderdetailInEditing[idx].minTmpid &&
							this.orderdetailInEditing[idx].minTmpid < minTmpid
						) {
							minTmpid = this.orderdetailInEditing[idx].minTmpid
						}
						if (
							this.orderdetailInEditing[idx].ProductionId &&
							this.orderdetailInEditing[idx].ProductionId ===
								productions[midx].AutoId
						) {
							this.$message('产品=' + productions[midx].Name + '已存在')
							skip = true
							break
						}
					}
					if (skip) {
						continue
					}
					let item = {
						AutoId: 0,
						minTmpid: minTmpid - 1,
						OrderId: this.ordermodelInEditing.AutoId
							? this.ordermodelInEditing.AutoId
							: 0,
						ProductionId: productions[midx].AutoId,
						ProductionStd: productions[midx].Specification,
						ProductionCode: productions[midx].Code,
						ProductionName: productions[midx].Name,
						ShortCode: productions[midx].ShortCode,
						Unit: productions[midx].Unit,
						PUnitCode: productions[midx].PUnitCode,
						UnitCode: productions[midx].UnitCode,
						Combination: productions[midx].Combination,
						Qty: 1,
						OrgPrice: productions[midx].Price,
						OrgAmount: productions[midx].Price * 1,
						PUnit: productions[midx].PUnit,
						OrderUnit: false,
						Price: 0,
						Amount: 0,
            OldNumber: productions[midx].OldNumber,
						GroupName: productions[midx].GroupName,
            SaleLv: productions[midx].SaleLv,
					}
					const loading = this.$loading({
						lock: true,
						text: 'Loading',
						spinner: 'el-icon-loading',
						background: 'rgba(0, 0, 0, 0.7)'
					})
					getPrice(item.ProductionId, item.Unit, null)
						.then(response => {
							if (response.Result === 0) {
								item.Price = response.Data.FPrice
								item.Amount = item.Price * item.Qty
								item.OrgPrice = item.Price
								item.OrgAmount = item.Price * item.Qty
							} else {
							}
							this.orderdetailInEditing.push(item)
							loading.close()
						})
						.catch(error => {
							this.$alert(error, '错误')
							this.orderdetailInEditing.push(item)
							loading.close()
						})
				}
			},
			addRowAndClose(productions) {
				this.addRow(productions)
				this.pickerVisible = false
			},
			rmRow() {
				const selectedData = this.$refs.oge.getSelected()
				if (selectedData.length === 0) {
					this.$message('请先选中需要删除的行')
					return
				}
				this.$confirm(
					'将会删除' + selectedData.length + '行记录,保存后生效。是否继续?',
					'提示',
					{ confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
				)
					.then(() => {
						for (let idx in selectedData) {
							for (let rIdx in this.orderdetailInEditing) {
								if (
									selectedData[idx].minTmpid ===
									this.orderdetailInEditing[rIdx].minTmpid
								) {
									this.orderdetailInEditing.splice(rIdx, 1)
									break
								}
							}
						}
					})
					.catch(error => {})
			}
		},
		created() {
			/*
		    let that = this
		    document.onkeydown = function(e) {
		      if (!that.dialogVisible) return
		      if (that.$refs.oge.getEditStatus().length > 0) return
		      if (window.event.keyCode != 40) return
		      const focused = that.$refs.oge.getFocused()
		      if (focused.rowIndex === focused.rows - 1) {
		        that.showPP()
		      }
		    }*/
		}
	}
</script>

<style>
	.el-span-c {
		padding: 5px;
		height: 40px;
		width: 100px;
		line-height: 30px;
		text-align: right;
	}
	.el-input-normal-c {
		width: 300px;
		height: 40px;
		text-align: left;
	}
	.el-input-large-c {
		width: 500px;
		height: 40px;
		text-align: left;
	}
	.el-low-c {
		height: 40px;
		margin-bottom: 15px;
		text-align: left;
	}
</style>
